import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form, Input, Button, Checkbox, message, Popover } from 'antd';
import { saveAs } from 'file-saver';
import Cookies from 'js-cookie';
import React, { useEffect, useMemo, useState } from 'react';
import { useDispatch, useSelector, history } from 'umi';

import Andon from '@/assets/images/Andon.svg';
import type { IReduxState } from '@/models/global';
import { namespace } from '@/models/global';
import type { OrderManageState } from '@/models/orderManage';
import { PRODCTION_NAME } from '@/pages/AddProductionLineUserNum';
import { getAllDocx } from '@/services/orderManage';
import { getErrorMsg, priceFormat } from '@/util/utils';

export interface AllReduxState {
  OrderManage: OrderManageState;
  GLOBAL_DATA: IReduxState;
}

import styles from './index.less';

const pattern = /^\+?[0-9]\d*$/;
const USER_INFO = JSON.parse(localStorage.getItem('USER_INFO') as string);
const versionsStorage = JSON.parse(localStorage.getItem('version') as string);
export default function ProOrder() {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const versions: any = useSelector<AllReduxState>((state) => state.OrderManage?.version);
  const [productLineNum, setProductLineNum] = useState(1);
  const [year, setYear] = useState(1);
  const [buttonVisible, setButtonVisible] = useState(true);
  const [buttonLoading, setButtonLoading] = useState<boolean>(false);
  useEffect(() => {
    dispatch({
      type: 'OrderManage/getVersion',
      payload: versionsStorage,
    });
  }, [dispatch, versionsStorage]);
  const getOrderType = useMemo(() => {
    switch (versions?.version) {
      case 'trail':
        return 3;
      case 'base':
        return 1;
      default:
        return 999;
    }
  }, [versions?.version]);

  const getTotalPric = useMemo(() => {

    let pri: number;
    if (form.getFieldValue('price')) {
      pri = form.getFieldValue('price');
      return priceFormat(Number(pri) * Number(year) * Number(productLineNum));
    } else {
      pri = 1980;
      return priceFormat(pri);
    }

  }, [form.getFieldValue('price'), year, productLineNum]);

  const onFinish = () => {
    const formValue = form.getFieldsValue();
    if (formValue.productionLineNum<=0 || formValue.payYear<=0) {
      return message.warn('产线数量和购买时长应该大于0！');
    }
    if (getOrderType !== 3) {
      if (!formValue.productionLineNum) {
        message.warn('请填写产线数量');
        return;
      } else if (!formValue.payYear) {
        message.warn('请填写购买时长');
        return;
      }
    }

    const createOrderParams = {
      orderType: getOrderType,
      companyName: USER_INFO?.companyName,
      saasProductId: versions?.id,
      unitPrice: getOrderType === 3 ? 0 : Number(formValue.price),
      discount: 0,
      paymentAmount: null,
      // paymentAmount: getOrderType === 3 ? 0 :
      //   Number(formValue.price) *
      //   Number(formValue.payYear) * Number(formValue.productionLineNum),
      buyTimes: getOrderType === 3 ? 3 : Number(formValue.payYear),
      buyedProductionLineNumber: getOrderType === 3 ? 1 : Number(formValue.productionLineNum),
      buyedPersonNumber: Number(formValue.userNum),
      buyUserId: '',
      buyTimeUnit: getOrderType === 3 ? 2 : 3,
    };
    form.validateFields().then(() => {
      setButtonLoading(true);
      dispatch({
        type: 'OrderManage/add',
        payload: createOrderParams,
        callback: (res: any) => {
          if (res.code == 200) {
            const formValues = {
              id: res.data.data,
              ...formValue,
            };
            localStorage.setItem('CURRENT_ORDER_INFO', JSON.stringify({
              ...formValues,
              totalPrice: getTotalPric,
            }));
            const timer = setTimeout(function() {
              try {
                if (getOrderType !== 3) {
                  setButtonLoading(false);
                  window.open('/OrderPay');
                }
                clearTimeout(timer);
              } catch (e) {
                console.log(e);
              }
            }, 0);
          } else {
            setButtonLoading(false);
            message.error(getErrorMsg(res));
          }
        },
      });
    });

    if (getOrderType === 3) {
      message.success('创建试用订单成功！即将跳转到登录页');
      dispatch({
        type: `${namespace}/getUserInfo`,
        callback() {
        },
      });
      history.push('/');
      setTimeout(() => {
        window.open('https://backend.chinairap.cn/');
      }, 1000);
    }
  };

  useEffect(() => {
    if (!Cookies.get('saas_token')) {
      return history.push('Login');
    }
    localStorage.removeItem('CURRENT_ORDER_INFO');
    form.setFieldsValue({
      productionLineNum: 1,
      payYear: getOrderType === 3 ? 3 : 1,
      orderType:
        versions?.version === 'trail'
          ? PRODCTION_NAME + '试用版'
          : versions?.version === 'base'
            ? PRODCTION_NAME + '标准版'
            : versions?.version === 'advanced'
              ? PRODCTION_NAME + '高级版'
              : '',
      price: versions?.price,
      companyName: USER_INFO?.companyName,
      phone: USER_INFO?.mobileNo,
    });
  }, [versions]);

  const changeProductionLineNum = (e: any) => {
    const value = Number(e.target.value);
    if (e.target.value === '') {
      return;
    }
    if (!pattern.test(e.target.value)) {
      form.setFieldsValue({
        productionLineNum: 1,
      });
      return message.warn('必须输入大于零的正整数');
    }
    if (value >= 1 && value <= 20) {
      form.setFieldsValue({
        price: 1980,
      });
    } else if (value >= 21 && value <= 30) {
      form.setFieldsValue({
        price: 1728,
      });
    } else if (value >= 31 && value <= 40) {
      form.setFieldsValue({
        price: 1584,
      });
    } else if (value >= 41 && value <= 50) {
      form.setFieldsValue({
        price: 1386,
      });
    } else if (value >= 51 && value <= 60) {
      form.setFieldsValue({
        price: 1188,
      });
    } else if (value > 60) {
      form.setFieldsValue({
        price: 990,
      });
    }
    setProductLineNum(Number(e.target.value));
  };
  const changeYear = (e: any) => {
    if (e.target.value === '') {
      return;
    }
    if (!pattern.test((e.target.value))) {
      form.setFieldsValue({
        payYear: 1,
      });
      return message.warn('必须输入大于零的正整数');
    }
    setYear(Number(e.target.value));
  };

  // document.body.scrollIntoView();
  return (
    <>
      <div className={styles.orderPayContent} style={{ background: 'rgb(248, 249, 252)' }}>
        <div className={styles.logo} onClick={() => history.push('/')}>
          <div>
            <img src={Andon} alt=""/>{' '}
          </div>
          <div>
            <div className={styles.andon}>Andon</div>
            <div className={styles.sys}>异常快速反应系统</div>
          </div>
        </div>
        <div className={styles.card}>
          <div className={styles.content}>
            <div className={styles.title} onClick={() => history.push('/')}>产品服务订单</div>
            <div className={styles.form}>
              <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} autoComplete="off">
                <Form.Item label="订购版本" name="orderType">
                  <Input disabled={true}/>
                </Form.Item>
                <Form.Item label="订购价格(￥)" name="price">
                  <Input disabled={true}/>
                </Form.Item>
                <Form.Item
                  label="企业全称"
                  name="companyName"
                  rules={[{ required: true, message: '请输入企业全称!' }]}
                >
                  <Input disabled={true}/>
                </Form.Item>
                <Form.Item
                  label="联系电话"
                  name="phone"
                  rules={[{ required: true, message: '请输入联系电话!' }]}
                >
                  <Input disabled={true}/>
                </Form.Item>

                {
                  getOrderType === 3 ? (
                      <Form.Item
                        label="产线数量"
                        name="productionLineNum"
                        rules={[{ required: true, message: '请输入产线数量!' }]}
                        getValueFromEvent={(e: any) => {
                          const { value } = e.target;
                          return value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '');
                        }}
                      >
                        <Input disabled={true} value={1} onChange={changeProductionLineNum} placeholder={'请输入产线数量'}/>
                      </Form.Item>
                    ) :
                    <Form.Item
                      label="产线数量"
                      name="productionLineNum"
                      rules={[{ required: true, message: '请输入产线数量!' }]}
                      getValueFromEvent={(e: any) => {
                        const { value } = e.target;
                        return value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '');
                      }}
                    >
                      <Input onChange={changeProductionLineNum} placeholder={'请输入产线数量'}/>
                    </Form.Item>
                }
                {
                  getOrderType === 3 ? (
                      <Form.Item
                        label="试用时长(月)"
                        name="payYear"
                        rules={[{ required: true, message: '请输入购买时长!' }]}
                        getValueFromEvent={(e: any) => {
                          const { value } = e.target;
                          return value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '');
                        }}
                      >
                        <Input value={3} disabled={true} onChange={changeYear} placeholder={'请输入购买时长'}/>
                      </Form.Item>
                    ) :
                    <Form.Item
                      label="购买时长(年)"
                      name="payYear"
                      rules={[{ required: true, message: '请输入购买时长!' }]}
                      getValueFromEvent={(e: any) => {
                        const { value } = e.target;
                        return value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '');
                      }}
                    >
                      <Input onChange={changeYear} placeholder={'请输入购买时长'}/>
                    </Form.Item>
                }
              </Form>
            </div>
          </div>
          <div className={styles.bottomContent}>
            <div className={styles.orderMoney}>
              订单金额{' '}
              <span>
              ￥{getOrderType === 3 ? 0.00 : getTotalPric}
                {/*  ￥{getOrderType === 3 ? 0.00 : priceFormat(Number(form.getFieldValue('price')) * year *Number(form.getFieldValue('productionLineNum')) || 1980)}*/}
          </span>
            </div>
            <div className={styles.des}>提交订单后可申请合同、开具发票</div>
            <div className={styles.des}> {getOrderType === 3 ? null : USER_INFO.hasTrialOrder ?
              <ExclamationCircleOutlined
                style={{ color: '#faac11' }}/> : null} {getOrderType === 3 ? null : USER_INFO.hasTrialOrder ? '当前账号下已经存在试用订单！' : null}</div>
            <div className={styles.agreeAndButton}>
              <Checkbox onChange={() => {
                setButtonVisible(!buttonVisible);
              }}/>
              &nbsp; &nbsp;同意&nbsp; &nbsp;
              <Popover content={(<div style={{ cursor: 'pointer', color: '#1a3dc9' }} onClick={ async () => {
                const res = await getAllDocx(2);
                if (res.code===200) {
                  const fileType = (res.data.path).split('.')[1];
                  saveAs('images/' + res.data.path, `芍园云软件付费服务协议.${fileType}`);
                } else {
                  message.error('下载错误！');
                }
              }}>芍园云软件付费服务协议</div>)} title="下载条款">
                <span onClick={() => window.open('Agreement?id=2')} className={styles.safe}>芍园云软件付费服务协议</span>
              </Popover>
              <Button loading={buttonLoading} type='primary' disabled={buttonVisible} onClick={onFinish}>
                提交订单
              </Button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
